<template>
  <page-lr>
      <el-form size="small" :model="searchForm" label-width="90px" slot="content-right">
        <el-form-item label="类型：">
          <el-radio-group v-model="searchForm.group_by_month" @change="changeType">
            <el-button size="small" :type="!searchForm.group_by_month ? 'primary' : 'default'" @click="changeType(false)">自定义统计</el-button>
            <el-button size="small" :type="searchForm.group_by_month ? 'primary' : 'default'" @click="changeType(true)">逐月统计</el-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="日期范围：">
          <el-date-picker v-if="searchForm.group_by_month" v-model="searchForm.year" type="year" value-format="yyyy" placeholder="选择年" @change="getOne"></el-date-picker>
          <my-dateRange v-else :start.sync="searchForm.start_date" :end.sync="searchForm.end_date" @change="getOne" style="width:100%" />
        </el-form-item>
      </el-form>
    <template slot="content-left">
      <el-row class="list-year" v-if="searchForm.group_by_month">
        <el-col v-for="(item,index) in list.year" :key="index" :xs="24">
          <v-chart :options="item" :autoresize="true" style="height:300px;width:100%;margin:30px 0"></v-chart>
        </el-col>
      </el-row>
      <el-row class="list-month" v-else>
        <el-col v-for="(item,index) in list.month" :key="index" :xs="24" :sm="8">
          <v-chart :options="item" :autoresize="true" style="height:300px;width:100%;margin:30px 0"></v-chart>
        </el-col>
      </el-row>
    </template>
  </page-lr>
</template>
<script>
export default {
  data() {
    return {
      searchForm:{
        start_date: '2023-01-01',
        end_date: '2023-05-18',
        group_by_month: false,
        year: '2023'
      },
      type: ['优','良','轻度污染','中度污染','重度污染','严重污染'],
      pie: {
        title: {
          text: '',
          left: 'center'
        },
        legend: {
          bottom: '0%',
          left: 'center',
          itemWidth: 10,
          // data:['优', '良', '轻度污染','中度污染','重度污染','严重污染'],
        },
        color: ['#EAEA26','#906BF9','#01E17E','#3DD1F9','#FE5656','#FFAD05'],
        series: [
          {
            name: '空气质量',
            type: 'pie',
            radius: '50%',
            // avoidLabelOverlap: false,
            label: {
              show: true,
              textStyle:{
                color:'#000',
              },
              formatter: '{b}：{d}%（{c}天）'
            },
            labelLine:{  
                normal:{  
                      length:1,  // 改变标示线的长度
                      lineStyle: {
                        color: "black"  // 改变标示线的颜色
                      }
                },
            },
            data: [
              { value: null, name:'SO₂', label: 'so2'},
              { value: null, name:'NO₂', label: 'no2' },
              { value: null, name:'PM₁₀', label: 'pm10' },
              { value: null, name:'PM₂.₅', label: 'pm25' },
              { value: null, name:'CO', label: 'co' },
              { value: null, name:'O₃_8h', label: 'o3_8h' }
            ]
          }
        ]
      },
      
      list:{
        month: [],
        year: [],
      }
    }
  },
  created() {
    this.searchForm.start_date = this.$moment().startOf('year').format('YYYY-MM-DD');
    this.searchForm.end_date = this.$moment().add(-1,'d').format('YYYY-MM-DD');
    this.getOne();
  },
  methods: {
    changeType(val){
      this.searchForm.group_by_month = val;
      this.getOne();
    },
    getParams(){
      let params = JSON.parse(JSON.stringify(this.searchForm));
      if(params.group_by_month){
        params.start_date = this.$moment(this.searchForm.year).startOf('year').format('YYYY-MM-DD');
        params.end_date = this.$moment(this.searchForm.year).endOf('year').format('YYYY-MM-DD');
      }
      return params;
    },
    getOne(){           
      this.$request('get', '/chaqi/city_primary_days_count', this.getParams(), (data,msg) => {
        this.getAll(data);
      })
    },
    getAll(result){
      let params = this.getParams();
      params.station_name ='ALL';
      this.$request('get', '/chaqi/station_primary_days_count', params, (data,msg) => {  
        let res = Object.assign({}, result, data);
        if(this.searchForm.group_by_month){
          this.getListYear(res);
        }else{    
          this.getListMonth(res);
        }
      })
    },
    getListMonth(res){
      this.list.month = [];
      for(let key in res){
        let obj = JSON.parse(JSON.stringify(this.pie));
        obj.title.text = key;
        obj.series[0].data.forEach((item,index) => {
          for(let key2 in res[key]){
            if(item.label == key2){
              obj.series[0].data[index].value = res[key][key2] == 0 ? null : res[key][key2];
            }
          }            
        });
        this.list.month.push(obj);
      };
    },
    getListYear(res){
      // let values = ['so2','no2','pm10','pm25','co','o3_8h'];
      // let values = ['SO₂', 'NO₂', 'PM₁₀','PM₂.₅','CO', 'O₃_8h'];
      let values = [
        { value: null, name:'SO₂', label: 'so2'},
        { value: null, name:'NO₂', label: 'no2' },
        { value: null, name:'PM₁₀', label: 'pm10' },
        { value: null, name:'PM₂.₅', label: 'pm25' },
        { value: null, name:'CO', label: 'co' },
        { value: null, name:'O₃_8h', label: 'o3_8h' }
      ]
      this.list.year = [];
      let seriesObj = {
            name: 'Direct',
            type: 'bar',
            barMaxWidth: 35,
            barGap: '10%',
            stack: 'total',
            data: [],
            itemStyle: {
              normal: {
                label: {
                  show: true,
                  position: 'inside',
                  fontSize: 14,
                  fontFamily: 'AlibabaPuHuiTi-Regular',
                  color: '#000'
                }
              }
            }
          };
      for(let key in res){
        let xAxisData = [];
        for(let i = 1; i < 13; i++){
          let month = i < 10 ? ('0'+ i) : i;
          xAxisData.push(this.searchForm.year + '-' + month);
        }
        let text = key;
        let series = [];
        
        let list = [];
        for(let key2 in res[key]){       
          list.push(res[key][key2]);
        }
        for(let i = 0; i< values.length; i++){
          let seriesObj2 = JSON.parse(JSON.stringify(seriesObj));
          seriesObj2.name = values[i].name;
          seriesObj2.data = list.map(item => {
            return item[values[i].label] == 0 ? null : item[values[i].label];
          })
          series.push(seriesObj2);          
        }
        let total = Array(12).fill(0);
        series.forEach((item,index) => {
          item.data.forEach((d,j) => {
            const val = d ? d : 0;
            total[j] = total[j] + val;
          })
        });        
        let seriesObj3 = {
          name: '有效天数',
          type: 'line',
          symbolSize: 1,
          itemStyle: {
            normal: {
              color: 'rgba(0,0,0,0)',
              label: {
                show: true,
                postion: 'top',
                fontSize: 15,
                fontFamily: 'AlibabaPuHuiTi-Bold',
                color: '#000',
                formatter: `{c}`
              }
            }
          },
          data: total.map(item => {
            return item > 0 ? item : null
          }),
        };        
        series.push(seriesObj3);
        let obj = {
          title: {
            text: text,
            left: 'center'
          },
          tooltip: {
            trigger: 'item',
            formatter: (params) => {
              let h = params.seriesName == '有效天数' ? '' : `<div>${params.seriesName}：${params.value}天</div>`
              return `<div>${params.name}</div>
                ${h}
                <div>有效天数：${total[params.dataIndex]}天</div>`
            },
            confine: true,
          },
          legend: {
            bottom: '0%',
            left: 'center',
            itemWidth: 10,
            data: values.map(item => item.name)
          },
          grid: {
            left: '3%',
            right: '4%',
            bottom: '10%',
            containLabel: true
          },
          color: ['#EAEA26','#906BF9','#01E17E','#3DD1F9','#FE5656','#FFAD05'],
          yAxis: {
            type: 'value',
            axisLabel: {
              formatter: "{value} 天",
            },
          },
          xAxis: {
            type: 'category',
            data: xAxisData
          },
          series: series
        };
        this.list.year.push(obj);
      }
    }
  }
}
</script>